package com.zx.common.tools.id.config;

import com.zx.common.tools.id.IdGenerator;
import com.zx.common.tools.id.IdGeneratorType;
import com.zx.common.tools.id.impl.SnowflakeIdGenerator;
import com.zx.common.tools.id.impl.UuidIdGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ID生成器配置类
 * 根据配置选择不同的ID生成策略
 */
@Configuration
public class IdGeneratorConfig {

    @Value("${id.generator.type}")
    private String idGeneratorType;

    @Value("${snowflake.datacenter.id}")
    private long datacenterId;

    @Value("${snowflake.worker.id}")
    private long workerId;

    @Bean
    @ConditionalOnProperty(name = "id.generator.type", havingValue = "uuid", matchIfMissing = false)
    public IdGenerator uuidIdGenerator() {
        return new UuidIdGenerator();
    }

    @Bean
    @ConditionalOnProperty(name = "id.generator.type", havingValue = "snowflake", matchIfMissing = true)
    public IdGenerator snowflakeIdGenerator() {
        return new SnowflakeIdGenerator(datacenterId, workerId);
    }

    @Bean
    public IdGenerator idGenerator() {
        IdGeneratorType type = IdGeneratorType.valueOf(idGeneratorType.toUpperCase());

        switch (type) {
            case UUID:
                return uuidIdGenerator();
            case SNOWFLAKE:
                return snowflakeIdGenerator();
            default:
                throw new IllegalArgumentException("Unsupported ID generator type: " + idGeneratorType);
        }
    }
}